'use strict';

const utils = require('utils/utils.js')
// 引入加密，解密模块
const bcrypt = require("bcryptjs");
const key = bcrypt.genSaltSync(10);  // 设置加密密钥

const Controller = require('egg').Controller;
 

class AdminController extends Controller {

  // 初始化，获取服务层的路径  
  AdminDataindex = this.ctx.service.admin.dataindex
  HomeDataindex = this.ctx.service.home.dataindex

  async index() {
    const {ctx} = this;
    ctx.body = 'admin, hello world';
  }

  // 解码token数据
  async validate() {
    const {ctx} = this;
    ctx.body = {code: 201, msg: '验证成功', data: ctx.state.user};
  }

  // 登录帐号，（返回token）
  async login() { 
    const {ctx, app} = this;
    const req = ctx.request.body;

    // 空值验证
    const errArr = app.validator.validate({
      username: 'string',
      password: 'string',
    }, req);

    if (errArr) {
      ctx.body = { error:JSON.stringify(errArr), code:403   }
      return;
    }

    let responseData = null;
    try { 
 
      // 获取用户信息
      // 通过服务层获取数据
      const paramsObj = {
        username:req.username,
        isDelete:'0'
      }  
      let data = await this.AdminDataindex.UserSelect(null,paramsObj,null,false) 
 
      let user = data.length ? data[0] : {}  
      // // 验证密码 
      const judge = bcrypt.compareSync(req.password,user.password)

      if (data.length && judge ) {  
        const {jwt: {secret, expiresIn}} = this.app.config;

        // 需传 secret 过期时间
        const token = this.app.jwt.sign({
          data:{
            id: user.id,
            username: user.username,
          },
        }, secret, {
          expiresIn,
        }); 

        // 更新token 
        const new_fieldObj = {
          token
        }
        const paramsObj = {
          id:user.id
        }
        const res = await this.AdminDataindex.UserUpdate(new_fieldObj,paramsObj)
   
        delete user['password']
        delete user['token']

        responseData = {  msg:'登录成功!',  token:token, userinfo:{...user,...new_fieldObj}, code:200 }
      } else {
        responseData = { msg:'登录失败', error:'用户名或密码不正确',  code:403 }
      }
    } catch (err) {
      responseData = { msg:"出现异常！",  error:err, code:500  }
    }
    ctx.body = responseData

  }

  // 退出登录
  async logout() {
    const {app,ctx} = this;
    const userinfo = ctx.state.user
    let responseData = null;
    try { 

      // 通过服务层获取数据
      const paramsObj = {
        id:userinfo.data.id,
        username:userinfo.data.username,
      }
      // 首个匹配的用户
      const data = await this.AdminDataindex.UserSelect(null,paramsObj) 
      if (data.length) {
        const user = data[0] ;
        // 更新token 
        const new_fieldObj = {
          token:''
        }
        const paramsObj = {
          id:user.id
        }
        const res = await this.AdminDataindex.UserUpdate(new_fieldObj,paramsObj)

        responseData = {  msg:'退出登录成功!',  code:204 }
      } else {
        responseData = { msg:'退出登录失败', error:'用户名认证出错！',  code:403 }
      }
    } catch (err) {
      responseData = { msg:"出现异常！",  error:err, code:500  }
    }
    ctx.body = responseData

  }

  // // 注册帐号
  async register() {
    const {ctx, app} = this;
    const req = ctx.request.body;

    // 空值验证
    const errArr = app.validator.validate({
      username: 'string',
      password: 'string',
      sex: 'string',
      address: 'string',
    }, req);
    if (errArr) {
      ctx.body = { error:JSON.stringify(errArr), code:403   }
      return;
    }

    let responseData = null;
    try {

      // 查询是否存在同昵称用户
      // 获取用户信息
      // 通过服务层获取数据
      const paramsObj = {
        username:req.username,
        // password:req.password,
        password:bcrypt.hashSync(req.password,key) ,
        isDelete:'0'
      }
      console.log("密码是",paramsObj)
      const data = await this.AdminDataindex.UserSelectFirst(paramsObj)
 
      if (!data ){
          // 注册新用户
          const paramsObj = {
            username:req.username,
            // password:req.password,
            password:bcrypt.hashSync(req.password,key) ,
            sex:req.sex,
            address:req.address,
            registerTime:utils.mysqlDateType(true),
            isDelete:'0'
          }  
          const res =await this.AdminDataindex.UserInsert(paramsObj)  
          responseData = {  msg:'注册成功!',  code:204 }
      } else {
        responseData = { msg:'注册失败！当前的昵称已经被注册',  code:403 }
      }
    } catch (err) {
      responseData = { msg:"出现异常！",  error:err, code:500  }
    }
    ctx.body = responseData
  }

  // // 注销帐号
  async unregister() {
    const {app,ctx} = this;
    const userinfo = ctx.state.user
    let responseData = null;
    try {
      // 通过服务层获取数据
      const paramsObj = {
        id:userinfo.data.id,
        username:userinfo.data.username,
      }
      // 首个匹配的用户
      const data = await this.AdminDataindex.UserSelect(null,paramsObj) 
      if (data.length) {
        const user = data[0] ;
        // 更新token  
        const new_fieldObj = { 
            token:'',
            isDelete:'1',
            deleteTime: utils.mysqlDateType()
        }
        const paramsObj = {
          id:user.id
        } 
        const res = await this.AdminDataindex.UserUpdate(new_fieldObj,paramsObj)
 
        responseData = {  msg:'注销帐号成功!',  code:204 }
      } else {
        responseData = { msg:'注销帐号失败', error:'用户名认证出错！',  code:403 }
      }
    } catch (err) {
      responseData = { msg:"出现异常！",  error:err, code:500  }
    }
    ctx.body = responseData
  }

}
module.exports = AdminController;